import React from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { Card, Icon, WhiteSpace, Grid, Flex, Button,Tools,ActivityIndicator,PullToRefresh } from 'weaver-mobile';
import { withRouter, Route } from 'react-router-dom';
import { SearchAdvanced, RouteLayout } from 'weaver-mobile-page';
import SellsReport from '../report/SellsReport';
import ContactRemindList from '../list/ContactRemindList';
import CustomerCard from '../card/Customer';
import ContactHomePage from '../list/ContactHomePage';
import CrmList from '../list/CrmList';

const getLabel = Tools.getLabel;

@inject('homePageStore')
@withRouter
@observer
export default class HomePage extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            reporttype: 'addCustomersCount',
            curCrmId: "",
            curWorkplanId: "",
            subType:"plan",
            comPath:"",
            comParams : ""
        };
    }

    componentWillMount() {
        this.props.homePageStore.doNew(this);
    }

    componentDidMount() {
        this.props.homePageStore.doInit();
    }

    componentWillUnmount() {
        this.props.homePageStore.doClear();
    }

    componentWillReceiveProps(nextProps) {
        const pn = this.props.location.pathname;
        const nn = nextProps.location.pathname;
        //日程页面回退,刷新今日计划
        if (pn.indexOf("workplanCreateLayout") != -1 || pn.indexOf("workplanViewLayout") != -1) {
            this.props.homePageStore.getContactPlan();
        }
    }    

    test=()=> {
        // window.history.pushState(null, null, document.URL);
        // this.props.history.goForward();
    }

    render() {

        const { history, homePageStore } = this.props;
        const { enters, sellchanceReports, search, sellChanceSearchStr, sellReportLayout, createdateselectParams, createrselectParams, portalLayout,remindLayout,contactPlanInfo,contactPlanLoading,workplanCreateLayout,workplanViewLayout,sellsReportLoading,remindLoading,remindInfo,customerCardLayout,refreshing,contactHomeLayout,enterLayout } = homePageStore;
        const { curCrmId,curWorkplanId,subType,comPath,comParams } = this.state;

        return (
            <div className="crm-homepage" style={{ height: "100%" }}>
                <PullToRefresh
                    damping={60}
                    style={{
                    height: "100%",
                    overflow: 'auto',
                    }}
                    direction={'down'}
                    refreshing={refreshing}
                    onRefresh={() => {
                        homePageStore.doInit();
                    }}
                >
                <WhiteSpace size="md" />
                <Card full>
                    <Card.Header
                        title={<span style={{ marginLeft: "5px", whiteSpace: "nowrap" }}>{getLabel(383307,'快捷入口') }</span>}
                        extra={<span></span>}
                    />
                    <Card.Body>
                        <div className='enters'><Grid data={enters} hasLine={false} square={false} isCarouse carouselMaxRow={2}  onClick={el =>{                                           
                            this.setState({comPath:el.comPath,comParams:el.comParams},()=>{
                                this.props.history.push(enterLayout.path);
                            });
                        }}/></div>{/** onClick={_el =>history.push(portalLayout.path)} */}
                        {/* <Route
                            key={portalLayout.id}
                            path={portalLayout.path}
                            render={() => {
                                return (
                                    <RouteLayout getContainer={() => document.getElementById("root")}>
                                        <div
                                            key="portalLayout"
                                            className="wm-route-layout"
                                        >
                                            <Enter params={{type: "crm_list", listTabIndex: "my"}}></Enter>
                                        </div>
                                    </RouteLayout>
                                )
                            }}
                        /> */}
                    </Card.Body>

                </Card>

                <WhiteSpace size="md" />
                <Card full>
                    <Card.Header
                        title={<span style={{ marginLeft: "5px", whiteSpace: "nowrap" }}>{getLabel(503783,'销售简报') }</span>}
                        extra={<span onClick={() => history.push(search.path)}>{sellChanceSearchStr}</span>}
                    />
                    <Card.Body>
                        {sellsReportLoading && <div className="crm-bg-loading"><ActivityIndicator text="Loading..." /></div>}
                        {!sellsReportLoading &&this.getSellChanceReportComp(toJS(sellchanceReports))}

                        <Route
                            key={sellReportLayout.id}
                            path={sellReportLayout.path}
                            render={() => {
                                let params = toJS({ ...createdateselectParams, ...createrselectParams, ...this.state });
                                let detailContent = <SellsReport params={params} formData={search.form.formData} />;
                                return (
                                    <RouteLayout getContainer={() => document.getElementById("root")}>
                                        <div
                                            key="sellReportLayout"
                                            className="wm-route-layout"
                                        >
                                            {detailContent}
                                        </div>
                                    </RouteLayout>
                                )
                            }}
                        />

                        <SearchAdvanced
                            store={search}
                            onChange={(condition, value) => homePageStore.getSellChanceSearchValue(value)}
                            onSubmit={() => homePageStore.getHpSellsInfo()}
                            onReset={() => homePageStore.getHpSellsReset()}
                        />
                    </Card.Body>

                </Card>

                {/* <WhiteSpace size="md" />
                <Card full>
                    <Card.Header
                        title={<span style={{ marginLeft: "5px", whiteSpace: "nowrap" }}>联系情况</span>}
                        extra={<span><Icon type={'right'} /></span>}
                    />
                    <Card.Body>
                        <div>This is content of `Card`</div>
                    </Card.Body>

                </Card> */}

                <WhiteSpace size="md" />
                <Card full>
                    <Card.Header
                        title={<span style={{ marginLeft: "5px", whiteSpace: "nowrap" }}>{getLabel(501587, "今日拜访计划")}
                        {contactPlanInfo.count !== 0 && "(" + contactPlanInfo.count + ")"}
                        </span>
                        }
                        extra={<span><Icon type={'right'}/></span>}
                        onClick={()=>{
                            this.props.history.push(contactHomeLayout.path);
                        }}
                    />
                    <Card.Body>
                        {
                            contactPlanLoading && <div className="crm-bg-loading"><ActivityIndicator text="Loading..." /></div>
                        }
                        {
                            !contactPlanLoading && contactPlanInfo.count === 0 &&
                            <div className="crm-homecard-new">
                                {/* <Icon className='icon' type={'blog-gengduo'} size='lg' onClick={() => {
                                    this.props.history.push(workplanCreateLayout.path);
                                }} /> */}
                                <div className="crm_phone" onClick={
                                    () => {
                                        this.props.history.push(workplanCreateLayout.path);
                                    }
                                }>{getLabel(503895,"立即创建")}</div>
                            </div>
                        }
                        {
                            !contactPlanLoading && contactPlanInfo.count > 0 &&
                            <div className="crm-homecard" onClick={()=>{
                                this.setState({curWorkplanId:contactPlanInfo.id});
                                this.props.history.push(workplanViewLayout.path);
                            }}>
                                <div className="crm-homecard-header">{contactPlanInfo.title}</div>
                                <div className="crm-homecard-footer">
                                    <div>{getLabel(503787,"计划起止时间")}</div>
                                    <div className="crm-homecard-footer-bottom">{contactPlanInfo.startTime} {getLabel("15322","至")} {contactPlanInfo.endTime}</div>
                                </div>
                            </div>
                        }
                    </Card.Body>
                </Card>

                <WhiteSpace size="md" />
                <Card full>
                    <Card.Header
                        title={<span style={{ marginLeft: "5px", whiteSpace: "nowrap" }}>{getLabel(503828,"遗忘客户提醒")}
                        {remindInfo.total !== 0 && "(" + remindInfo.total + ")"}
                        </span>}
                        extra={<span><Icon type={'right'} /></span>}
                        onClick={()=>history.push(remindLayout.path)}
                    />
                    <Card.Body>
                        {
                            remindLoading && <div className="crm-bg-loading"><ActivityIndicator text="Loading..." /></div>
                        }
                        {
                            !remindLoading && remindInfo.total === 0 &&
                            <div className="crm-homecard-new">
                                {getLabel(126307,"暂无记录")}
                            </div>
                        }
                        {
                            !remindLoading && remindInfo.total > 0 &&
                            <div className="crm-homecard" onClick={()=>{
                                this.setState({curCrmId:remindInfo.customerId});
                                this.props.history.push(customerCardLayout.path);
                            }}>
                            <div className="crm-homecard-header">{remindInfo.customerName}</div>
                            <div className="crm-homecard-follow">
                                <div className="crm-homecard-footer">
                                    {
                                        remindInfo.lastestContactDate === "" && 
                                        <div className="crm-homecard-footer-bottom">{getLabel(503829,"无跟进记录")}</div>
                                    }
                                    {
                                        remindInfo.lastestContactDate !== "" &&
                                        <div>
                                            <div>{getLabel(503788,"最后跟进时间")}</div>
                                            <div className="crm-homecard-footer-bottom">{remindInfo.lastestContactDate}</div>
                                        </div>                                        
                                    }                                    
                                </div>
                                {
                                    remindInfo.lastestContactDate !== "" &&
                                    <div className="crm-homecard-tip">
                                    {getLabel(503791,"距离上次跟进")}<span className="crm-homecard-tip-days">{remindInfo.uncontactDate}</span>{getLabel(1925,'天')}
                                    </div>
                                }                                
                            </div>
                        </div>
                        }
                    </Card.Body>
                </Card>
                <RouteLayout.Frame
                    id="workplanCreateLayout"
                    path={workplanCreateLayout.path}
                    iframeProps={{
                        src: "/spa/workplan/static4mobile/index.html#/create?fromType=crm&workPlanTypeOptions=3",
                    }}
                />
                <RouteLayout.Frame
                    id="workplanViewLayout"
                    path={workplanViewLayout.path}
                    iframeProps={{
                        src: "/spa/workplan/static4mobile/index.html#/detail?fromType=crm&workplanId=" + curWorkplanId,
                    }}
                />
                <Route
                    key={remindLayout.id}
                    path={remindLayout.path}
                    render={() => {
                        return (
                            <RouteLayout getContainer={() => document.getElementById("root")}>
                                <div
                                    key="remindLayout"
                                    className="wm-route-layout"
                                >
                                    <ContactRemindList />
                                </div>
                            </RouteLayout>
                        )
                    }}
                /> 
                <Route
                    key={customerCardLayout.id}
                    path={customerCardLayout.path}
                    render={() => {
                        // 客户卡片
                        let detailContent = <CustomerCard params={{ id: curCrmId }}/>
                        return (
                        <RouteLayout getContainer={() => document.getElementById("root")}>
                            <div
                            key="customerCardLayout"
                            className="wm-route-layout"
                            >
                            {detailContent}
                            </div>
                        </RouteLayout>
                        )
                    }}
                />
                <Route
                    key={contactHomeLayout.id}
                    path={contactHomeLayout.path}
                    render={() => {
                        return (
                            <RouteLayout getContainer={() => document.getElementById("root")}>
                                <div
                                    key="contactHomeLayout"
                                    className="wm-route-layout"
                                >
                                    <ContactHomePage params={{subType:subType}}/>
                                </div>
                            </RouteLayout>
                        )
                    }}
                /> 
                <Route
                    key={enterLayout.id}
                    path={enterLayout.path}
                    render={() => {
                        return (
                            <RouteLayout getContainer={() => document.getElementById("root")}>
                                <div
                                    key="crmListLayout"
                                    className="wm-route-layout"
                                >
                                    {(comPath === "../list/CrmList" && <CrmList params={comParams}/>)}
                                    {(comPath === "../list/ContactHomePage" && <ContactHomePage params={comParams}/>)}
                                </div>
                            </RouteLayout>
                        )
                    }}
                /> 
                </PullToRefresh>
            </div>

        );
    }

    getSellChanceReportComp = (sellchanceReports) => {
        const { sellReportLayout } = this.props.homePageStore;
        let flexComp = [];
        let flexItemComp = [];

        let newArray = [];
        for (let i = 0; i < sellchanceReports.length; i += 2) {
            newArray.push(sellchanceReports.slice(i, i + 2));
        }

        newArray.forEach((flex, findex) => {
            flexItemComp = [];
            flex.forEach((item, iindex) => {
                flexItemComp.push(<Flex.Item className='crm-home-sells-item' key={`item${iindex}`}
                    onClick={() => { this.state.reporttype = item.type, this.props.history.push(sellReportLayout.path) }}>
                        <div className={"crm-home-sells-item-icon iconfont "+item.icon}></div>
                        <div className='crm-home-sells-item-content'>
                            <div className='crm-home-sells-item-content-text'>{item.text}</div>
                            <div className='crm-home-sells-item-content-count'>{item.counts}</div>
                        </div>
                </Flex.Item>);
            })
            flexComp.push(<Flex key={`flex${findex}`}>{flexItemComp}</Flex>);
        });

        return <div className='crm-home-sells'>
            {flexComp}
        </div>
    }
}